﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Cit.CDE.Net.Service.ModuleFactory;
using Cit.CDE.Net.Module;
using System.Collections.Generic;
using Cit.CDE.Net.Module.Commons;
using cde.SystemCommon;
using Cit.CDE.Net.Service;
using System.Text;

using Module;
using Telerik.WebControls;
using System.IO;


/// <summary>
/// Copyright (C)   jinggubang
/// FileName:        CourseEdit.aspx.cs           
/// Author :         wangbc
/// CDT:             2012-02-01           
/// Version:         1.0.0.0                
/// Depiction:       课件新增    
/// </summary>
public partial class main_admin_CourseEdit : UserControl.CommonPage
{
    /// <summary>
    /// 课件EM
    /// </summary>
    private CDEEntityManager em;
    /// <summary>
    /// 课件Entity
    /// </summary>
    private CDEEntity m_entity;
    /// <summary>
    /// 课件Entity名字
    /// </summary>    
    private  string EM_FULL_NAME = WEBConstants.EM_CSW_MANAGE;

    /// <summary>
    /// 操作员ID
    /// </summary>
    private string opId;

    /// <summary>
    /// 管理员标识
    /// </summary>
    public string admin;

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {

        //当前登陆人信息
        LoginOprator op = (LoginOprator)Session[Cit.CDE.Net.Module.Commons.CDEConstants.SESSION_LOIN_OPRATOR];
        opId = op.SysID;
        

        //课件ID
        string chkID = (string)Request.QueryString.Get("chkID");

        //管理员标识
        admin = Util.objectToString(Request.QueryString.Get("admin"));


        em = CDEEMFactory.getEMByFullName(EM_FULL_NAME);
        if (!Page.IsPostBack)
        {
            //ID不为空修改课件，否则新增课件
            if (chkID != "" && chkID != null)
            {
                //修改
                this.page_title.InnerText = "课件修改";
                CDESearchCriteria sc = new CDESearchCriteria(em);
                sc.addCondition("ID", chkID);
                List<CDEEntity> listEntity = CDEService.LoadEntities(em, sc);
                //课件ID是否存在
                if (listEntity.Count > 0)
                {
                    m_entity = listEntity[0];
                    m_entity.Operation = CDEDataOperation.UPDATE;
                }
                else
                {
                    m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                    m_entity.Operation = CDEDataOperation.INSERT;
                }
            }
            else
            {
                //新增
                this.page_title.InnerText = "课件新增";
                m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                m_entity.Operation = CDEDataOperation.INSERT;
                
            }
            Session["MENTITY"] = m_entity;

            //修改时显示新增用户文件夹,新增时显示当前用户文件夹
            string flo_user_id = opId;
            if (m_entity.Operation == CDEDataOperation.UPDATE) {
                flo_user_id = Util.objectToString(m_entity.get("INSERT_USER"));            
            }

            DropDownList fol_id = (DropDownList)this.ddl_FOL_ID__FOL_NAME;
            fol_id.Attributes["TiaoJian"] = "INSERT_USER|" + flo_user_id + "|3";

            //课件信息设值到页面
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);

            //文件名画面显示
            string fileName = Util.objectToString(m_entity.get("FILE_PATH"));
            if (fileName != "")
            {
                this.showFile.Style.Value = "display:block";
                this.file_name.InnerHtml = fileName;
                this.upFile.Style.Value = "display:none";
            }
        }
        else
        {
            m_entity = (CDEEntity)Session["MENTITY"];
            //页面信息放入课件Entity
            this.setEntityFromRequest(m_entity, Request.Params);
        }
    }
    /// <summary>
    /// 确定按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void queding_Click(object sender, EventArgs e)
    {
        
        //当前时间
        string Now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");
        if (m_entity.Operation == CDEDataOperation.INSERT)
        {
            m_entity.set("INSERT_USER", opId);
            m_entity.set("INSERT_DATE", Now);
        }
        else
        {
            m_entity.set("UPDATE_USER", opId);
            m_entity.set("UPDATE_DATE", Now);
        }
        //系统信息存入Session
        Sys_Info sysInfo = (Sys_Info)Session[WEBConstants.SYS_INFO_SESSION_ID];
        if (sysInfo != null) {
            string audit = sysInfo.AUDIT; //0:不审核,1:审核

            //如果系统不需要审核,直接把状态修改为已审核,否则为未审核
            if (audit == "0")
            {
                m_entity.set("AUDIT_STATE", 1); //0:未审核,1:已审核
            }
            else {
                m_entity.set("AUDIT_STATE", 0); //0:未审核,1:已审核
            }
        }

      
        List<CDEEntity> listEntity = new List<CDEEntity>();

        listEntity.Add(m_entity);

        bool isSaveError = false;

        string chkID = (string)Request.QueryString.Get("chkID");

        CDESearchCriteria vsc = new CDESearchCriteria(em);
        //更新,否则新增
        if (chkID != null)
        {
            vsc.addCondition("ID", chkID, CDEConstCompare.Inequality);            
        }
        vsc.addCondition("NAME", m_entity.get("NAME"));
        vsc.addCondition("DEL_FLG", "0");
        vsc.addCondition("INSERT_USER", opId); 

        List<CDEEntity> vListEntity = CDEService.LoadEntities(em, vsc);

        //课件名称存在不执行更新,不存在执行更新
        if (vListEntity.Count > 0)
        {
            showMessageErrAndOk("该课件名称已经存在！");
            isSaveError = true;
        }
        else
        {
            CDEService.UpdateEntities(em, listEntity);

            if (listEntity[0].Result == CDEDataOperationResult.ERROR)
            {
                isSaveError = true;
            }
            else
            {
                //上传的文件重合名为课件ID
                // string Path = Server.MapPath(@"~/Uploads");
                string Path = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["Courseware"]); 

                string oldFileName = Path +  m_entity.get("FILE_PATH");
                string newFileName = Path +  m_entity.get("CSW_ID");

                if (File.Exists(oldFileName))
                {
                    if (File.Exists(newFileName))
                    {
                        File.Delete(newFileName);
                    }
                    File.Move(oldFileName, newFileName);
                } 

                isSaveError = false;
            }
        }

        
        

        //成功返回列表，失败提示错误信息
        if (isSaveError)
        {
            showMessageErrAndOk(Resources.ResourceErrMsg.SAVE_ERR);
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);
        }
        else
        {

            //管理员操作返回
            if (admin.Equals("1"))
            {
                EM_FULL_NAME = "WEB.CSW_MANAGE_ADMIN";
            }

            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            sbr.AppendFormat("alert(\"");
            sbr.AppendFormat(Resources.Resource.RESULT_OK);
            sbr.AppendFormat("\");window.location='../course/CourseList.aspx?EM=" + EM_FULL_NAME + "&sel_menu_id=" + Sel_MenuNode.Attributes["id"].Value + "&IsBackSc=1';</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
        }

    }
    /// <summary>
    /// 返回按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        //管理员操作返回
        if (admin.Equals("1"))
        {
            EM_FULL_NAME = "WEB.CSW_MANAGE_ADMIN";
        }


        if (Sel_MenuNode == null)
            return;
        StringBuilder url = new StringBuilder();
        url.Append("../course/CourseList.aspx?EM=");
        url.Append(EM_FULL_NAME);
        url.Append("&sel_menu_id=");
        url.Append(Sel_MenuNode.Attributes["id"].Value);
        url.Append("&IsBackSc=1");
        Response.Redirect(url.ToString());

    }


    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
           // string Path = Server.MapPath(@"~/Uploads");
            string Path =  Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["Courseware"]); 

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }

            //课件名称默认为文件名
            string fileName = file.GetName().ToString();
            this.txt_NAME.Text = fileName;

            //组合路径，file.GetName()取得文件名
            Path = Path +  fileName;

            //保存
            file.SaveAs(Path, true);

            //设置文件信息
            m_entity.set("FILE_SIZE", file.ContentLength);
            m_entity.set("FILE_PATH",file.GetName());
            m_entity.set("FILE_TYPE",file.GetExtension().ToLower());


            this.showFile.Style.Value = "display:block";
            this.file_name.InnerHtml = file.GetName().ToString();
            this.upFile.Style.Value = "display:none";
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDelFile_Click(object sender, EventArgs e)
    {

        this.showFile.Style.Value = "display:none";
        this.file_name.InnerHtml = "";
        this.upFile.Style.Value = "display:block";
    }
}
